import {Base64} from './base64'
import {httpBaseUrl} from './config'
import { Web_Socket } from './socket';
const http = {}

let once = false;

const navigateToLogin = (code, msg) => {
    if (!once) {
        once = true;
        wx.showModal({
          title: '',
          content: code ? (msg) : '认证失败，请重新登录',
          confirmColor: wx.$theme.color,
          confirmText: "去登陆",
          complete: (res) => {
            wx.removeStorageSync('szm_token');
            once = false;
            if (res.confirm) {
              const pgs = getCurrentPages();
              if (pgs[pgs.length - 1].route.indexOf('/login') === -1) {
                  wx.navigateTo({
                    url: '/pages/login/index',
                  })
              }
            }
          }
        })
    }
}

const request = ({url, method, data, responseType, showLoading = true, noToken, otherBaseUrl}) => {
    const {token, expire} = wx.getStorageSync('szm_token');
    if ( !noToken && !token) {
        navigateToLogin();
        return Promise.reject();
    }
    const header = {
        token: token,
        'content-type': 'application/json'
    }
    const link = (otherBaseUrl || httpBaseUrl) + url
    console.log(link, '=>', method, data)
    if (url.includes('netty/post') && !Web_Socket.connect) { //尝试重连接websocket
        Web_Socket.buildSocket();
    }
    return new Promise((resolve, reject) => {
        
        showLoading && wx.$eventEmitter.emit("showLoading", 1)
        wx.request({
            header: header,
            url: link,
            data: data,
            method: method,
            timeout: 70000,
            responseType: responseType || 'text',
            success(res) {
                showLoading && wx.$eventEmitter.emit("showLoading", 0);
                const {statusCode, data, header} = res;
                console.log(link, '<=', res)
                if (statusCode === 200) {
                    const ct = header['Content-Type'];
                    if(/image/.test(ct)) {
                        const imgB64 = 'data:' + ct + ';base64,' +  Base64.bA2B64(data);
                        resolve(imgB64); //返回图片
                    } else {
                        const {code, msg} = data;
                        if (code === 0) {
                            resolve(data)//正常返回
                        } else if (code === 10020 || code === 10021) {
                            navigateToLogin(code, msg);//校验token失败
                        } else{
                            wx.showToast({
                              title: msg,
                              icon: 'none'
                            })
                            reject(data);//业务异常
                        }
                    }
                } else {
                    wx.showToast({
                        title: statusCode + ' ' + (/^4\d+/.test(statusCode+ '') ? '请求异常' : '服务器异常'),
                        icon: 'none'
                    })
                    reject(res);//服务器异常
                }
            },
            fail(err) {
                showLoading && wx.hideLoading();
                wx.showToast({
                    title: '网络异常',
                    icon: 'none'
                  })
                reject(err);//网络异常
            },
            complete() {
                // showLoading && wx.hideLoading();
            }
        })
    })
}

//const {url, data, responseType, showLoading} = param
http['get'] = (param) => {
    return request({method: 'GET', ...param});
}
http['post'] = (param) => {
    return request({method: 'POST', ...param});
}
http['put'] = (param) => {
    return request({method: 'PUT', ...param});
}
http['delete'] = (param) => {
    return request({method: 'DELETE', ...param});
}

export default http;